#########################################################################
# File Name: prepare_data.py
# Author: caochenglong
# mail: caochenglong@163.com
# Created Time: 2017-07-24 14:50:43
# Last modified:2017-07-24 15:04:51
#########################################################################
# !/usr/bin/python3
# _*_coding: utf-8_*_

import json
import rdflib
import uuid
from urllib.parse import quote
import re


class DataProcessor(object):

    def __init__(self, filename):
        self._filepath = "data/%s" % filename
        self._data
        self._ids = {}

    @property
    def _data(self):
        data = []
        with open(self._filepath, "r") as f:
            lines = f.readlines()
            for line in lines:
                data.append(json.loads(line))
        return data

    def _get_id(self, ent):
        if ent in self._ids:
            return self._ids[ent]
        u_id = str(uuid.uuid3(uuid.NAMESPACE_OID, ent))
        u_id = u_id.replace('-', '')
        self._ids[ent] = "jd_" + u_id
        return self._ids[ent]

    def _format_att(self, att):
        att = att.strip()
        att = re.sub(r'（.*）', '', att)
        att = re.sub(r'\\*\/*', '', att)
        return att

    def process(self):
        base_url = "http://cogik/linguistic/resourse/entitys/"
        COGIK_JD = rdflib.Namespace(base_url + "cogikjd#")
        g = rdflib.ConjunctiveGraph()
        g.bind('cogik', COGIK_JD)
        for d in self._data:
            for att in d['attr']:
                s = rdflib.URIRef(base_url + self._get_id(d['label']))
                g.add((s, rdflib.RDF.type, COGIK_JD['Product']))
                g.add((s, COGIK_JD['label'],
                       rdflib.Literal(d['label'])))
                if att == '品牌':
                    attr_list = []
                    if not isinstance(d['attr'][att], list):
                        attr_list.append(d['attr'][att])
                    else:
                        attr_list = d['attr'][att]
                    for brand in attr_list:
                        brand = brand.strip()
                        o = rdflib.URIRef("%s%s" %
                                          (base_url, self._get_id(brand)))
                        g.add((o, COGIK_JD['label'],
                               rdflib.Literal(brand)))
                        #  has_product = rdflib.URIRef(
                        #  "%s/hasproduct" % base_url)
                        #  g.add(
                        #      (has_product, rdflib.RDF.type,
                        #       COGIK_JD['hasProduct']))
                        #  has_brand = rdflib.URIRef("
                        #  %s/hasbrand" % base_url)
                        #  g.add(
                        #      (has_brand, rdflib.RDF.type,
                        #  COGIK_JD['hasBrand']))
                        g.add((s, COGIK_JD['hasBrand'], o))
                        g.add((o, rdflib.RDF.type, COGIK_JD['Brand']))
                        g.add((o, COGIK_JD['hasProduct'], s))
                elif att == '大家说':
                    attr_list = []
                    if not isinstance(d['attr'][att], list):
                        attr_list.append(d['attr'][att])
                    else:
                        attr_list = d['attr'][att]
                    for talk in attr_list:
                        talk = talk.strip()
                        #  has_rev = rdflib.URIRef("%s/hasrev" % base_url)
                        #  g.add((has_rev, rdflib.RDF.type,
                        #  COGIK_JD['hasRev']))

                        o = rdflib.Literal(talk)
                        g.add((o, rdflib.RDF.type, COGIK_JD['resview']))
                        g.add((s, COGIK_JD['hasRev'], o))
                else:
                    attr_list = []
                    if not isinstance(d['attr'][att], list):
                        attr_list.append(d['attr'][att])
                    else:
                        attr_list = d['attr'][att]
                    for at in attr_list:
                        at = at.strip()
                        #  has_attr_str = ("%s/%s" % (base_url, att))
                        #  has_attr = rdflib.URIRef(quote(has_attr_str))
                        #  g.add((has_attr, rdflib.RDF.type,
                        #         COGIK_JD[quote(att)]))
                        o = rdflib.Literal(at)
                        g.add((o, rdflib.RDF.type, COGIK_JD['attribute']))
                        # print(att)
                        # print(quote(att))
                        g.add((s, COGIK_JD[self._format_att(att)], o))
        g.serialize("jd.rdf")


if __name__ == "__main__":
    dp = DataProcessor("products_more")
    dp.process()
